import React, { Component,/*PureComponent*/ } from "react";

// API
import {getSms} from "../../api/account";
// antd
import { Button } from "antd";
// 验证

let timer = null;

// class 组件
export default class Code extends Component {
    constructor(props){
        super(props); // 初始化默认值
        this.state = {
            username: props.username,
            button_text: "获取验证码",
            button_loading: false,
            button_disabled: false,
            module: props.module,
            initValue: {}
        }
    }
    componentWillReceiveProps = (nextProps) =>{
        this.setState({
            ...this.state,
            module:nextProps.module,
            username:nextProps.username
        })
    }
    componentWillUnmount() {
        clearInterval(timer);
    }
    /*    shouldComponentUpdate(a,b){
            console.log(a,b);
            //返回true  渲染组件 false 不渲染组件
            return true;
        }*/
    getCode = ()=>{
        this.setState({
            ...this.state,
            button_loading:true,
            button_disabled:true,
        })
        getSms({
            username:this.state.username,
            module:this.state.module
        }).then(e=>{
            this.setState({
                ...this.state,
                button_disabled:true,
                button_loading:false
            })
            let num = 60;
            timer = setInterval(()=>{
                this.setState({
                    ...this.state,
                    button_text:`${num}s`
                })
                num--;
                if(num<0){
                    clearInterval(timer);
                    this.setState({
                        ...this.state,
                        button_text:`获取验证码`,
                        button_disabled:false
                    })
                }
            },1000)
        }).catch(e=>{
            console.log(e)
            this.setState({
                ...this.state,
                button_disabled:false,
                button_loading:false
            })
        })
    }

    render(){
        return <Button type="danger" disabled={this.state.button_disabled} loading={this.state.button_loading} block onClick={this.getCode}>{this.state.button_text}</Button>
    }
}


